﻿using Microsoft.Extensions.Logging;

namespace SimpleX.Application;

public class StudentService : DbRepository<Student>, IStudentService
{
    private readonly ILogger<StudentService> _logger;
    private readonly ICacheService _cacheService;

    public StudentService(ILogger<StudentService> logger,
        ICacheService cacheService)
    {
        _logger = logger;
        _cacheService = cacheService;
    }

    public async Task<SqlSugarPagedList<Student>> Page(StudentPageInput input)
    {
        var query = Context.Queryable<Student>()
                           //.WhereIF(!string.IsNullOrEmpty(input.SearchKey), it => it.Name.Contains(input.SearchKey))//根据关键字查询
                           .OrderByIF(!string.IsNullOrEmpty(input.SortField), $"{input.SortField} {input.SortOrder}");

        var pageInfo = await query.ToPagedListAsync(input.Current, input.Size);//分页
        return pageInfo;
    }

    public async Task Add(StudentAddInput input)
    {
        var student = input.Adapt<Student>();//实体转换
        await CheckInput(student);//检查参数
        await InsertAsync(student);//插入数据
    }

    public async Task Edit(StudentEditInput input)
    {
        var student = input.Adapt<Student>();//实体转换
        await CheckInput(student);//检查参数
        await UpdateAsync(student);//更新数据
    }

    public async Task Delete(List<BaseIdInput> input)
    {
        //获取所有ID
        var ids = input.Select(it => it.Id).ToList();
        if (ids.Count > 0)
        {
            await DeleteByIdsAsync(ids.Cast<object>().ToArray());//删除数据
        }
        _logger.LogInformation($"delete student:{ids.Count}");
    }

    public async Task<Student> Detail(BaseIdInput input)
    {
        var student = await GetFirstAsync(it => it.Id == input.Id);
        return student;
    }

    public async Task<dynamic> Score(BaseIdInput input)
    {
        var ck = _cacheService.AcquireLock($"Key:{input.Id}", 5000);
        try
        {
            var student = await GetByIdAsync(input.Id);
            if (student == null)
            {
                return Unify.SetError("学生不存在");
            }

            if (student.Score <= 0)
            {
                return Unify.SetError("学生分不够扣的了");
            }

            var score = student.Score - 1;

            await UpdateAsync(x => new Student
            {
                Score = score
            }, x => x.Id == input.Id);

            Console.WriteLine($"扣分完成,学生当前分数:{score}");
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            ck.Dispose();
        }

        return default;
    }

    private async Task CheckInput(Student student)
    {
        await Task.CompletedTask;
    }
}